import*as e from"../../../core/common/common.js";import*as t from"../../../core/i18n/i18n.js";import*as r from"../../../ui/legacy/legacy.js";import*as n from"../../../core/sdk/sdk.js";import*as i from"../../../services/puppeteer/puppeteer.js";import*as a from"../../../core/platform/platform.js";import*as o from"../util/util.js";var s,c,l,d=Object.freeze({__proto__:null});!function(e){e.CSS="css",e.ARIA="aria",e.Text="text",e.XPath="xpath",e.Pierce="pierce"}(s=s||(s={})),function(e){e.Change="change",e.Click="click",e.Close="close",e.CustomStep="customStep",e.DoubleClick="doubleClick",e.EmulateNetworkConditions="emulateNetworkConditions",e.Hover="hover",e.KeyDown="keyDown",e.KeyUp="keyUp",e.Navigate="navigate",e.Scroll="scroll",e.SetViewport="setViewport",e.WaitForElement="waitForElement",e.WaitForExpression="waitForExpression"}(c=c||(c={})),(l=l||(l={})).Navigation="navigation";Object.freeze({__proto__:null,get SelectorType(){return s},get StepType(){return c},get AssertedEventType(){return l}});function u(e){throw new Error(`Unknown step type: ${e.type}`)}const p=new Set(["textarea","text","url","tel","search","password","number","email"]),g=new Set(["mouse","pen","touch"]),h=new Map([["primary","left"],["auxiliary","middle"],["secondary","right"],["back","back"],["forward","forward"]]);function f(e,t){return!!Object.prototype.hasOwnProperty.call(e,t)&&void 0!==e[t]}function w(e){return"object"==typeof e&&null!==e}function m(e){return"string"==typeof e}function y(e){return"number"==typeof e}function v(e){return Array.isArray(e)}function b(e){if(f(e,"target")&&m(e.target))return e.target}function S(e){if(f(e,"frame")){if(v(t=e.frame)&&t.every((e=>Number.isInteger(e))))return e.frame;throw new Error("Step `frame` is not an integer array")}var t}function E(e,t){if(f(e,t)){const r=e[t];if(y(r))return r}throw new Error(`Step.${t} is not a number`)}function T(e,t){if(f(e,t)){const r=e[t];if("boolean"==typeof r)return r}throw new Error(`Step.${t} is not a boolean`)}function k(e,t){if(f(e,t))return E(e,t)}function C(e,t){if(f(e,t))return N(e,t)}function M(e,t){if(f(e,t))return T(e,t)}function N(e,t){if(f(e,t)){const r=e[t];if(m(r))return r}throw new Error(`Step.${t} is not a string`)}function x(e){if(!f(e,"selectors"))throw new Error("Step does not have required selectors");if(!v(e.selectors))throw new Error("Step selectors are not an array");if(0===e.selectors.length)throw new Error("Step does not have required selectors");return e.selectors.map((e=>{if(!m(e)&&!v(e))throw new Error("Selector is not an array or string");return v(e)?e.map((e=>{if(!m(e))throw new Error("Selector element is not a string");return e})):e}))}function L(e){if(f(e,"selectors"))return x(e)}function R(e){if(!w(e))throw new Error("Asserted event is not an object");if(!f(e,"type"))throw new Error("Asserted event is missing type");if(e.type===l.Navigation)return{type:l.Navigation,url:C(e,"url"),title:C(e,"title")};throw new Error("Unknown assertedEvent type")}function F(e){if(v(e))return e.map(R)}function A(e,t){if(f(t,"timeout")&&y(t.timeout)&&!W(t.timeout))throw new Error(j);return{type:e,assertedEvents:f(t,"assertedEvents")?F(t.assertedEvents):void 0,timeout:f(t,"timeout")&&y(t.timeout)?t.timeout:void 0}}function P(e,t){return{...A(e,t),target:b(t)}}function _(e,t){return{...P(e,t),frame:S(t)}}function I(e,t){return{..._(e,t),selectors:x(t)}}function O(e){const t={offsetX:E(e,"offsetX"),offsetY:E(e,"offsetY"),duration:k(e,"duration")},r=C(e,"deviceType");if(r){if("string"!=typeof(n=r)||!g.has(n))throw new Error(`'deviceType' for click steps must be one of the following: ${[...g].join(", ")}`);t.deviceType=r}var n;const i=C(e,"button");if(i){if(!function(e){return"string"==typeof e&&h.has(e)}(i))throw new Error(`'button' for click steps must be one of the following: ${[...h.keys()].join(", ")}`);t.button=i}return t}function $(e,t){if(!w(e))throw new Error(t?`Step ${t} is not an object`:"Step is not an object");if(!f(e,"type"))throw new Error(t?`Step ${t} does not have a type`:"Step does not have a type");if(!m(e.type))throw new Error(t?`Type of the step ${t} is not a string`:"Type of the step is not a string");switch(e.type){case c.Click:return function(e){return{...I(c.Click,e),...O(e),type:c.Click}}(e);case c.DoubleClick:return function(e){return{...I(c.DoubleClick,e),...O(e),type:c.DoubleClick}}(e);case c.Hover:return function(e){return{...I(c.Hover,e),type:c.Hover}}(e);case c.Change:return function(e){return{...I(c.Change,e),type:c.Change,value:N(e,"value")}}(e);case c.KeyDown:return function(e){return{...P(c.KeyDown,e),type:c.KeyDown,key:N(e,"key")}}(e);case c.KeyUp:return function(e){return{...P(c.KeyUp,e),type:c.KeyUp,key:N(e,"key")}}(e);case c.EmulateNetworkConditions:return function(e){return{...P(c.EmulateNetworkConditions,e),type:c.EmulateNetworkConditions,download:E(e,"download"),upload:E(e,"upload"),latency:E(e,"latency")}}(e);case c.Close:return function(e){return{...P(c.Close,e),type:c.Close}}(e);case c.SetViewport:return function(e){return{...P(c.SetViewport,e),type:c.SetViewport,width:E(e,"width"),height:E(e,"height"),deviceScaleFactor:E(e,"deviceScaleFactor"),isMobile:T(e,"isMobile"),hasTouch:T(e,"hasTouch"),isLandscape:T(e,"isLandscape")}}(e);case c.Scroll:return function(e){return{..._(c.Scroll,e),type:c.Scroll,x:k(e,"x"),y:k(e,"y"),selectors:L(e)}}(e);case c.Navigate:return function(e){return{...P(c.Navigate,e),type:c.Navigate,target:b(e),url:N(e,"url")}}(e);case c.CustomStep:return function(e){if(!f(e,"name"))throw new Error("customStep is missing name");if(!m(e.name))throw new Error("customStep's name is not a string");return{..._(c.CustomStep,e),type:c.CustomStep,name:e.name,parameters:f(e,"parameters")?e.parameters:void 0}}(e);case c.WaitForElement:return function(e){const t=C(e,"operator");if(t&&">="!==t&&"=="!==t&&"<="!==t)throw new Error("WaitForElement step's operator is not one of '>=','==','<='");if(f(e,"attributes")&&(!w(e.attributes)||Object.values(e.attributes).some((e=>"string"!=typeof e))))throw new Error("WaitForElement step's attribute is not a dictionary of strings");if(f(e,"properties")&&!w(e.properties))throw new Error("WaitForElement step's attribute is not an object");return{...I(c.WaitForElement,e),type:c.WaitForElement,operator:t,count:k(e,"count"),visible:M(e,"visible"),attributes:f(e,"attributes")?e.attributes:void 0,properties:f(e,"properties")?e.properties:void 0}}(e);case c.WaitForExpression:return function(e){if(!f(e,"expression"))throw new Error("waitForExpression step is missing `expression`");return{..._(c.WaitForExpression,e),type:c.WaitForExpression,expression:N(e,"expression")}}(e);default:throw new Error(`Step type ${e.type} is not supported`)}}function D(e){const t=[];if(!v(e))throw new Error("Recording `steps` is not an array");for(const[r,n]of e.entries())t.push($(n,r));return t}const j="Timeout is not between 1 and 30000 milliseconds";function W(e){return e>=1&&e<=3e4}function U(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function B(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r}function K(e,t){const r=[];return V(e,r,1,t),r.join("")}function V(e,t=[],r=1,n="  "){switch(typeof e){case"bigint":case"symbol":case"function":case"undefined":throw new Error("Invalid JSON");case"number":case"boolean":t.push(String(e));break;case"string":t.push(J(e));break;case"object":if(null===e)t.push("null");else if(Array.isArray(e)){t.push("[\n");for(let i=0;i<e.length;i++)t.push(n.repeat(r)),V(e[i],t,r+1,n),i!==e.length-1&&t.push(","),t.push("\n");t.push(n.repeat(r-1)+"]")}else{t.push("{\n");const i=Object.keys(e);for(let a=0;a<i.length;a++){const o=i[a],s=e[o];void 0!==s&&(t.push(n.repeat(r)),t.push(o),t.push(": "),V(s,t,r+1,n),a!==i.length-1&&t.push(","),t.push("\n"))}t.push(n.repeat(r-1)+"}")}break;default:throw new Error("Unknown object type")}return t}new WeakMap,new WeakMap,new WeakMap;const z=(e,t)=>e.toString(16).toUpperCase().padStart(t,"0"),H=new Map([["\b","\\b"],["\f","\\f"],["\n","\\n"],["\r","\\r"],["\t","\\t"],["\v","\\v"],["'","\\'"],["\\","\\\\"],["\x3c!--","\\x3C!--"],["<script","\\x3Cscript"],["</script","\\x3C/script"]]),J=e=>{const t=/(\\|<(?:!--|\/?script))|(\p{Control})|(\p{Surrogate})/gu,r=(e,t,r,n)=>r?H.has(r)?H.get(r):"\\x"+z(r.charCodeAt(0),2):n?"\\u"+z(n.charCodeAt(0),4):t?H.get(t)||"":e;let n="",i="";return e.includes("'")?e.includes('"')?e.includes("`")||e.includes("${")?(i="'",n=e.replace(/(\\|'|<(?:!--|\/?script))|(\p{Control})|(\p{Surrogate})/gu,r)):(i="`",n=e.replace(t,r)):(i='"',n=e.replace(t,r)):(i="'",n=e.replace(t,r)),`${i}${n}${i}`};var X,Y,G,q,Q,Z,ee,te,re,ne,ie,ae,oe,se,ce,le,de;X=new WeakSet,Y=function(e,t){"main"===t?e.appendLine("const targetPage = page;"):(e.appendLine(`const target = await browser.waitForTarget(t => t.url() === ${K(t,e.getIndent())}, { timeout });`),e.appendLine("const targetPage = await target.page();"),e.appendLine("targetPage.setDefaultTimeout(timeout);"))},G=function(e,t){e.appendLine("let frame = targetPage.mainFrame();");for(const r of t)e.appendLine(`frame = frame.childFrames()[${r}];`)},q=function(e,t){e.appendLine(`await scrollIntoViewIfNeeded(${K(t.selectors,e.getIndent())}, ${t.frame?"frame":"targetPage"}, timeout);`),e.appendLine(`const element = await waitForSelectors(${K(t.selectors,e.getIndent())}, ${t.frame?"frame":"targetPage"}, { timeout, visible: true });`)},Q=function(e,t){U(this,X,"m",q).call(this,e,t),e.appendLine("await element.click({"),t.duration&&e.appendLine(`  delay: ${t.duration},`),t.button&&e.appendLine(`  button: '${h.get(t.button)}',`),e.appendLine("  offset: {"),e.appendLine(`    x: ${t.offsetX},`),e.appendLine(`    y: ${t.offsetY},`),e.appendLine("  },"),e.appendLine("});")},Z=function(e,t){U(this,X,"m",q).call(this,e,t),e.appendLine("await element.click({"),t.button&&e.appendLine(`  button: '${h.get(t.button)}',`),e.appendLine("  offset: {"),e.appendLine(`    x: ${t.offsetX},`),e.appendLine(`    y: ${t.offsetY},`),e.appendLine("  },"),e.appendLine("});"),e.appendLine("await element.click({"),e.appendLine("  clickCount: 2,"),t.duration&&e.appendLine(`  delay: ${t.duration},`),t.button&&e.appendLine(`  button: '${h.get(t.button)}',`),e.appendLine("  offset: {"),e.appendLine(`    x: ${t.offsetX},`),e.appendLine(`    y: ${t.offsetY},`),e.appendLine("  },"),e.appendLine("});")},ee=function(e,t){U(this,X,"m",q).call(this,e,t),e.appendLine("await element.hover();")},te=function(e,t){U(this,X,"m",q).call(this,e,t),e.appendLine("const inputType = await element.evaluate(el => el.type);"),e.appendLine("if (inputType === 'select-one') {"),e.appendLine(`  await changeSelectElement(element, ${K(t.value,e.getIndent())})`),e.appendLine(`} else if (${K(Array.from(p),e.getIndent())}.includes(inputType)) {`),e.appendLine(`  await typeIntoElement(element, ${K(t.value,e.getIndent())});`),e.appendLine("} else {"),e.appendLine(`  await changeElementValue(element, ${K(t.value,e.getIndent())});`),e.appendLine("}")},re=function(e,t){e.appendLine("await targetPage.emulateNetworkConditions({"),e.appendLine(`  offline: ${!t.download&&!t.upload},`),e.appendLine(`  downloadThroughput: ${t.download},`),e.appendLine(`  uploadThroughput: ${t.upload},`),e.appendLine(`  latency: ${t.latency},`),e.appendLine("});")},ne=function(e,t){e.appendLine(`await targetPage.keyboard.down(${K(t.key,e.getIndent())});`)},ie=function(e,t){e.appendLine(`await targetPage.keyboard.up(${K(t.key,e.getIndent())});`)},ae=function(e,t){e.appendLine("await targetPage.close()")},oe=function(e,t){e.appendLine(`await targetPage.setViewport(${K({width:t.width,height:t.height},e.getIndent())})`)},se=function(e,t){"selectors"in t?(U(this,X,"m",q).call(this,e,t),e.appendLine(`await element.evaluate((el, x, y) => { el.scrollTop = y; el.scrollLeft = x; }, ${t.x}, ${t.y});`)):e.appendLine(`await targetPage.evaluate((x, y) => { window.scroll(x, y); }, ${t.x}, ${t.y})`)},ce=function(e,t){e.appendLine(`await targetPage.goto(${K(t.url,e.getIndent())});`)},le=function(e,t){e.appendLine(`await ${t.frame?"frame":"targetPage"}.waitForFunction(${K(t.expression,e.getIndent())}, { timeout });`)},de=function(e,t){e.appendLine(`await waitForElement(${K(t,e.getIndent())}, ${t.frame?"frame":"targetPage"}, timeout);`)};const ue="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";ue.split("").reduce(((e,t,r)=>(e.set(t,r),e)),new Map);class pe{async beforeAllSteps(e){}async afterAllSteps(e){}async beforeEachStep(e,t){}async runStep(e,t){}async afterEachStep(e,t){}}var ge,he,fe;const we={"==":(e,t)=>e===t,">=":(e,t)=>e>=t,"<=":(e,t)=>e<=t};class me extends pe{constructor(e,t,r){super(),ge.add(this),this.browser=e,this.page=t,this.timeout=(null==r?void 0:r.timeout)||5e3}async runStep(e,t){const r=U(this,ge,"m",fe).call(this,e,t),n=this.page,i=this.browser,a=await async function(e,t,r,n){if(!r.target||"main"===r.target)return t;const i=await e.waitForTarget((e=>e.url()===r.target),{timeout:n}),a=await i.page();return a?(a.setDefaultTimeout(n),a):null}(i,n,e,r);let o=null;if(!a&&e.target){const t=n.frames();for(const r of t)if(r.isOOPFrame()&&r.url()===e.target){o=r;break}o||(o=await n.waitForFrame(e.target,{timeout:r}))}const s=o||a;if(!s)throw new Error("Target is not found for step: "+JSON.stringify(e));await U(this,ge,"m",he).call(this,s);const c=await async function(e,t){let r="mainFrame"in e?e.mainFrame():e;if("frame"in t&&t.frame)for(const e of t.frame)r=r.childFrames()[e];return r}(s,e);await this.runStepInFrame(e,n,s,c,r)}async runStepInFrame(e,t,r,n,i){const a=!0;let o=null;const s=()=>{o=async function(e,t,r){const n=[];if(t.assertedEvents)for(const i of t.assertedEvents){if(i.type!==l.Navigation)throw new Error(`Event type ${i.type} is not supported`);n.push(e.waitForNavigation({timeout:r}))}await Promise.all(n)}(n,e,i)};switch(e.type){case c.DoubleClick:{await ve(e.selectors,n,i);const t=await be(e.selectors,n,{timeout:i,visible:a});if(!t)throw new Error("Could not find element: "+e.selectors[0]);s(),await t.click({button:e.button&&h.get(e.button),offset:{x:e.offsetX,y:e.offsetY}}),await t.click({clickCount:2,button:e.button&&h.get(e.button),delay:e.duration,offset:{x:e.offsetX,y:e.offsetY}}),await t.dispose()}break;case c.Click:{await ve(e.selectors,n,i);const t=await be(e.selectors,n,{timeout:i,visible:a});if(!t)throw new Error("Could not find element: "+e.selectors[0]);s(),await t.click({delay:e.duration,button:e.button&&h.get(e.button),offset:{x:e.offsetX,y:e.offsetY}}),await t.dispose()}break;case c.Hover:{await ve(e.selectors,n,i);const t=await be(e.selectors,n,{timeout:i,visible:a});if(!t)throw new Error("Could not find element: "+e.selectors[0]);s(),await t.hover(),await t.dispose()}break;case c.EmulateNetworkConditions:s(),await t.emulateNetworkConditions(e);break;case c.KeyDown:s(),await t.keyboard.down(e.key),await t.waitForTimeout(100);break;case c.KeyUp:s(),await t.keyboard.up(e.key),await t.waitForTimeout(100);break;case c.Close:"close"in r&&(s(),await r.close());break;case c.Change:{await ve(e.selectors,n,i);const t=await be(e.selectors,n,{timeout:i,visible:a});if(!t)throw new Error("Could not find element: "+e.selectors[0]);const r=await t.evaluate((e=>e.type));s(),"select-one"===r?await this.changeSelectElement(e,t):p.has(r)?await this.typeIntoElement(e,t):await this.changeElementValue(e,t),await t.dispose()}break;case c.SetViewport:"setViewport"in r&&(s(),await r.setViewport(e));break;case c.Scroll:if("selectors"in e){await ve(e.selectors,n,i);const t=await be(e.selectors,n,{timeout:i,visible:a});s(),await t.evaluate(((e,t,r)=>{e.scrollTop=r,e.scrollLeft=t}),e.x||0,e.y||0),await t.dispose()}else s(),await n.evaluate(((e,t)=>{window.scroll(e,t)}),e.x||0,e.y||0);break;case c.Navigate:s(),await n.goto(e.url);break;case c.WaitForElement:try{s(),await async function(e,t,r){const{count:n=1,operator:i=">=",visible:a=!0,properties:o,attributes:s}=e,c=we[i];await Te((async()=>{const r=await async function(e,t){for(const r of e){const e=await Ee(r,t);if(e.length)return e}return[]}(e.selectors,t);let i=c(r.length,n);const l=await t.evaluateHandle(((...e)=>e),...r);return await Promise.all(r.map((e=>e.dispose()))),i&&(o||s)&&(i=await l.evaluate(((e,t,r)=>{if(r)for(const t of e)for(const[e,n]of Object.entries(r))if(t.getAttribute(e)!==n)return!1;if(t)for(const r of e)if(!n(t,r))return!1;return!0;function n(e,t){if(e===t)return!0;if(e&&!t||!e&&t)return!1;if(!(e instanceof Object&&t instanceof Object))return!1;for(const[r,i]of Object.entries(e))if(!n(i,t[r]))return!1;return!0}}),o,s)),await l.dispose(),i===a}),r)}(e,n,i)}catch(e){throw"Timed out"===e.message?new Error("waitForElement timed out. The element(s) could not be found."):e}break;case c.WaitForExpression:s(),await n.waitForFunction(e.expression,{timeout:i});break;case c.CustomStep:break;default:u(e)}await o}async typeIntoElement(e,t){const r=await t.evaluate(((e,t)=>{if(t.length<=e.value.length||!t.startsWith(e.value))return e.value="",t;const r=e.value;return e.value="",e.value=r,t.substring(r.length)}),e.value);await t.type(r)}async changeElementValue(e,t){await t.focus(),await t.evaluate(((e,t)=>{e.value=t,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}),e.value)}async changeSelectElement(e,t){await t.select(e.value),await t.evaluateHandle((e=>{e.blur(),e.focus()}))}}ge=new WeakSet,he=async function(e){try{await e._client().send("Emulation.setAutomationOverride",{enabled:!0})}catch{}},fe=function(e,t){return e.timeout||(null==t?void 0:t.timeout)||this.timeout};class ye extends me{async afterAllSteps(){await this.browser.close()}}async function ve(e,t,r){const n=await be(e,t,{visible:!1,timeout:r});if(!n)throw new Error("The element could not be found.");await async function(e,t){await Te((async()=>await e.evaluate((e=>e.isConnected))),t)}(n,r);const i=await(async e=>await e.evaluate((e=>e instanceof SVGElement))?e:null)(n),a=i?await async function(e){return await e.evaluateHandle((e=>{var t;return null!==(t=e.ownerSVGElement)&&void 0!==t?t:e}))}(i):n;a&&await a.isIntersectingViewport({threshold:0})||(await async function(e){await e.evaluate((e=>{e.scrollIntoView({block:"center",inline:"center",behavior:"auto"})}))}(n),a&&await async function(e,t){await Te((async()=>await e.isIntersectingViewport({threshold:0})),t)}(a,r),await a.dispose(),a!==n&&await n.dispose())}async function be(e,t,r){for(const n of e)try{return await Se(n,t,r)}catch(e){console.error("error in waitForSelectors",e)}throw new Error("Could not find element for selectors: "+JSON.stringify(e))}async function Se(e,t,r){if(Array.isArray(e)||(e=[e]),!e.length)throw new Error("Empty selector provided to `waitForSelector`");let n=1===e.length,i=await t.waitForSelector(e[0],{...r,visible:n&&r.visible});for(const t of e.slice(1,e.length)){if(!i)throw new Error("Could not find element: "+e.join(">>"));const a=await i.evaluateHandle((e=>e.shadowRoot?e.shadowRoot:e));i.dispose(),n=e[e.length-1]===t,i=await a.waitForSelector(t,{...r,visible:n&&r.visible}),a.dispose()}if(!i)throw new Error("Could not find element: "+e.join(">>"));return i}async function Ee(e,t){if(Array.isArray(e)||(e=[e]),!e.length)throw new Error("Empty selector provided to querySelectorAll");let r=await t.$$(e[0]);if(!r.length)return[];for(const t of e.slice(1,e.length))if(r=(await Promise.all(r.map((async e=>{const r=await e.evaluateHandle((e=>e.shadowRoot?e.shadowRoot:e)),n=await r.$$(t);return r.dispose(),e.dispose(),n})))).flat(),!r.length)return[];return r}async function Te(e,t){let r=!0;const n=setTimeout((()=>{r=!1}),t);for(;r;){if(await e())return void clearTimeout(n);await new Promise((e=>setTimeout(e,100)))}throw new Error("Timed out")}var ke,Ce,Me;async function Ne(e,t,r){var n,i;await(null===(n=e.beforeEachStep)||void 0===n?void 0:n.call(e,t,r)),await e.runStep(t,r),await(null===(i=e.afterEachStep)||void 0===i?void 0:i.call(e,t,r))}class xe{constructor(e){ke.set(this,void 0),Ce.set(this,void 0),Me.set(this,!1),B(this,Ce,e,"f")}abort(){B(this,Me,!0,"f")}set flow(e){B(this,ke,e,"f")}async runBeforeAllSteps(e){var t,r;await(null===(r=(t=U(this,Ce,"f")).beforeAllSteps)||void 0===r?void 0:r.call(t,e))}async runAfterAllSteps(e){var t,r;await(null===(r=(t=U(this,Ce,"f")).afterAllSteps)||void 0===r?void 0:r.call(t,e))}async runStep(e){await Ne(U(this,Ce,"f"),e)}async run(){var e,t,r,n,i,a;if(!U(this,ke,"f"))throw new Error("Set the flow on the runner instance before calling `run`.");const o=U(this,ke,"f");if(B(this,Me,!1,"f"),await(null===(t=(e=U(this,Ce,"f")).beforeAllSteps)||void 0===t?void 0:t.call(e,o)),U(this,Me,"f"))return!1;for(const e of o.steps){if(U(this,Me,"f"))return await(null===(n=(r=U(this,Ce,"f")).afterAllSteps)||void 0===n?void 0:n.call(r,o)),!1;await Ne(U(this,Ce,"f"),e,o)}return await(null===(a=(i=U(this,Ce,"f")).afterAllSteps)||void 0===a?void 0:a.call(i,o)),!0}}ke=new WeakMap,Ce=new WeakMap,Me=new WeakMap;new WeakMap;new WeakMap,new WeakMap,new WeakMap;var Le=Object.freeze({__proto__:null,get AssertedEventType(){return l},get StepType(){return c},get SelectorType(){return s}});const Re={defaultRecordingName:"Recording {DATE} at {TIME}"},Fe=t.i18n.registerUIStrings("panels/recorder/models/RecorderSettings.ts",Re),Ae=t.i18n.getLocalizedString.bind(void 0,Fe);var Pe=Object.freeze({__proto__:null,RecorderSettings:class{#e=e.Settings.Settings.instance().createSetting("recorderSelectorAttribute","");#t=e.Settings.Settings.instance().createSetting("recorderPanelReplaySpeed","normal");#r=e.Settings.Settings.instance().createSetting("recorderPanelReplayExtension","");#n=new Map;#i=e.Settings.Settings.instance().createSetting("recorder_preferred_copy_format","json");constructor(){for(const t of Object.values(s))this.#n.set(t,e.Settings.Settings.instance().createSetting(`recorder${t}SelectorEnabled`,!0))}get selectorAttribute(){return this.#e.get()}set selectorAttribute(e){this.#e.set(e)}get speed(){return this.#t.get()}set speed(e){this.#t.set(e)}get replayExtension(){return this.#r.get()}set replayExtension(e){this.#r.set(e)}get defaultTitle(){const e=new Date;return Ae(Re.defaultRecordingName,{DATE:e.toLocaleDateString(),TIME:e.toLocaleTimeString()})}get defaultSelectors(){return Object.values(s).filter((e=>this.getSelectorByType(e)))}getSelectorByType(e){return this.#n.get(e)?.get()}setSelectorByType(e,t){this.#n.get(e)?.set(t)}get preferredCopyFormat(){return this.#i.get()}set preferredCopyFormat(e){this.#i.set(e)}}});var _e=Object.freeze({__proto__:null,RecorderShortcutHelper:class{#a;#o=null;#s;constructor(e=200){this.#s=e,this.#a=new AbortController}#c(){this.#a.abort(),this.#o&&clearTimeout(this.#o),this.#a=new AbortController}#l(e){this.#c(),e()}handleShortcut(e){this.#c(),document.addEventListener("keyup",(t=>{r.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(t)&&this.#l(e)}),{signal:this.#a.signal}),this.#o=setTimeout((()=>this.#l(e)),this.#s)}}});const Ie={normal:0,slow:500,very_slow:1e3,extremely_slow:2e3};function Oe(e,t){return!t.url.startsWith("chrome-extension://")&&(!(!t.url.startsWith("devtools://")||t.targetId!==e)||("page"===t.type||"iframe"===t.type)&&(t.targetId===e||t.openerId===e||"iframe"===t.type))}function $e(e){return e.url.startsWith("devtools://")||"page"===e.type||"background_page"===e.type||"webview"===e.type}class De extends e.ObjectWrapper.ObjectWrapper{#d;#u;userFlow;speed;timeout;breakpointIndexes;steppingOver=!1;aborted=!1;abortPromise;#p;#g;constructor(e,{speed:t,breakpointIndexes:r=new Set}){super(),this.userFlow=e,this.speed=t,this.timeout=e.timeout||5e3,this.breakpointIndexes=r,this.#d=new Promise((e=>{this.#u=e})),this.abortPromise=new Promise((e=>{this.#p=e}))}#h(){this.#u?.(),this.#d=new Promise((e=>{this.#u=e}))}static async connectPuppeteer(){const e=n.TargetManager.TargetManager.instance().primaryPageTarget();if(!e)throw new Error("Could not find main target");const t=e.model(n.ChildTargetManager.ChildTargetManager);if(!t)throw new Error("Could not get childTargetManager");const r=e.model(n.ResourceTreeModel.ResourceTreeModel);if(!r)throw new Error("Could not get resource tree model");const a=r.mainFrame;if(!a)throw new Error("Could not find main frame");const o=(await t.createParallelConnection((()=>{}))).connection,s=await t.getParentTargetId(),{page:c,browser:l,puppeteerConnection:d}=await i.PuppeteerConnection.PuppeteerConnectionHelper.connectPuppeteerToConnection({connection:o,mainFrameId:a.id,targetInfos:t.targetInfos(),targetFilterCallback:Oe.bind(null,s),isPageTargetCallback:$e});if(!c)throw new Error("could not find main page!");return l.on("targetdiscovered",(e=>{"page"===e.type&&e.targetId!==s&&e.openerId===s&&d._createSession(e,!0)})),{page:c,browser:l}}static async disconnectPuppeteer(e){try{const t=await e.pages();for(const e of t){const t=e._client();await t.send("Network.disable"),await t.send("Page.disable"),await t.send("Log.disable"),await t.send("Performance.disable"),await t.send("Runtime.disable"),await t.send("Emulation.clearDeviceMetricsOverride"),await t.send("Emulation.setAutomationOverride",{enabled:!1});for(const t of e.frames()){const e=t._client();await e.send("Network.disable"),await e.send("Page.disable"),await e.send("Log.disable"),await e.send("Performance.disable"),await e.send("Runtime.disable"),await e.send("Emulation.setAutomationOverride",{enabled:!1})}}e.disconnect()}catch(e){console.error("Error disconnecting Puppeteer",e.message)}}async stop(){await Promise.race([this.#d,this.abortPromise])}abort(){this.aborted=!0,this.#p?.(),this.#g?.abort()}disposeForTesting(){this.#u?.(),this.#p?.()}continue(){this.steppingOver=!1,this.#h()}stepOver(){this.steppingOver=!0,this.#h()}updateBreakpointIndexes(e){this.breakpointIndexes=e}async play(){const e=n.TargetManager.TargetManager.instance().primaryPageTarget();e&&await e.pageAgent().invoke_setPrerenderingAllowed({isAllowed:!1});const{page:t,browser:r}=await De.connectPuppeteer();this.aborted=!1;const i=this;const a=new class extends me{#t;constructor(e,t,{timeout:r,speed:n}){super(e,t,{timeout:r}),this.#t=n}async beforeEachStep(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));i.dispatchEventToListeners("Step",{step:e,resolve:r}),await n;const a=t.steps.indexOf(e),o=i.steppingOver||i.breakpointIndexes.has(a),s="setViewport"!==e.type&&"navigate"!==e.type&&!i.aborted;o?(i.dispatchEventToListeners("Stop"),await i.stop(),i.dispatchEventToListeners("Continue")):s&&await Promise.race([new Promise((e=>setTimeout(e,Ie[this.#t]))),i.abortPromise])}async runStep(e,r){if(!t?.url().startsWith("devtools://")||"setViewport"!==e.type&&"navigate"!==e.type)return await super.runStep(e,r)}}(r,t,{timeout:this.timeout,speed:this.speed});let o;this.#g=await async function(e,t){const r=e instanceof pe?e:t,n=e instanceof pe?void 0:e,i=new xe(null!=r?r:await async function(){const{default:e}=await import("puppeteer"),t=await e.launch({headless:!0}),r=await t.newPage();return new ye(t,r)}());return n&&(i.flow=n),i}(this.userFlow,a);try{await this.#g.run()}catch(e){o=e,console.error("Replay error",e.message)}finally{const e=n.TargetManager.TargetManager.instance().primaryPageTarget();e&&await e.pageAgent().invoke_setPrerenderingAllowed({isAllowed:!0}),await De.disconnectPuppeteer(r)}this.aborted?this.dispatchEventToListeners("Abort"):o?this.dispatchEventToListeners("Error",o):this.dispatchEventToListeners("Done")}}var je=Object.freeze({__proto__:null,defaultTimeout:5e3,shouldAttachToTarget:Oe,RecordingPlayer:De});function We(e){return{type:c.SetViewport,width:e.clientWidth,height:e.clientHeight,deviceScaleFactor:1,isMobile:!1,hasTouch:!1,isLandscape:!1}}function Ue(e){return{type:c.EmulateNetworkConditions,...e}}function Be(e,t){return"selectors"in e&&"selectors"in t?JSON.stringify(e.selectors)===JSON.stringify(t.selectors):!("selectors"in e)&&!("selectors"in t)}const Ke=function(e){if(!w(e))throw new Error("Recording is not an object");if(!f(e,"title"))throw new Error("Recording is missing `title`");if(!m(e.title))throw new Error("Recording `title` is not a string");if(f(e,"timeout")&&!y(e.timeout))throw new Error("Recording `timeout` is not a number");if(!f(e,"steps"))throw new Error("Recording is missing `steps`");if(f(e,"timeout")&&y(e.timeout)&&!W(e.timeout))throw new Error(j);return t={title:e.title,timeout:f(e,"timeout")&&y(e.timeout)?e.timeout:void 0,selectorAttribute:f(e,"selectorAttribute")&&m(e.selectorAttribute)?e.selectorAttribute:void 0,steps:D(e.steps)},JSON.parse(JSON.stringify(t));var t},Ve=$;var ze=Object.freeze({__proto__:null,createViewportStep:We,createEmulateNetworkConditionsStep:Ue,areSelectorsEqual:Be,minTimeout:1,maxTimeout:3e4,parse:Ke,parseStep:Ve});function He(e){return n.TargetManager.TargetManager.instance().primaryPageTarget()===e||"main"===e.id()?"main":e.inspectedURL()}function Je(e,t){const r=[];for(;t;){const e=t.sameTargetParentFrame();if(!e)break;const n=e.childFrames.indexOf(t);r.unshift(n),t=e}return{target:He(e),frame:r}}async function Xe(e,t,r){const i=t.model(n.RuntimeModel.RuntimeModel).executionContexts(),a=t.model(n.ResourceTreeModel.ResourceTreeModel);for(const n of a.frames()){if(!i.find((e=>e.frameId===n.id)))continue;const{executionContextId:a}=await t.pageAgent().invoke_createIsolatedWorld({frameId:n.id,worldName:e});await t.runtimeAgent().invoke_evaluate({expression:r,includeCommandLineAPI:!0,contextId:a})}}var Ye=Object.freeze({__proto__:null,getTargetName:He,getTargetFrameContext:Je,evaluateInAllFrames:Xe,findTargetByExecutionContext:function(e,t){for(const r of e){const e=r.model(n.RuntimeModel.RuntimeModel);if(e)for(const n of e.executionContexts())if(n.id===t)return r}},findFrameIdByExecutionContext:function(e,t){for(const r of e){const e=r.model(n.RuntimeModel.RuntimeModel);if(e)for(const r of e.executionContexts())if(r.id===t&&void 0!==r.frameId)return r.frameId}},isFrameTargetInfo:e=>"page"===e.type||"iframe"===e.type});const Ge=a.StringUtilities.formatAsJSLiteral,qe=new Set(["typed","address_bar","auto_bookmark","auto_subframe","generated","auto_toplevel","reload","keyword","keyword_generated"]),Qe=Object.freeze({addStep:"addStep",stopShortcut:"stopShortcut"});class Ze extends e.ObjectWrapper.ObjectWrapper{#f;#w;#m;#y;#v;#b=new Map;#S=new Map;#E=new Map;#T=new Map;#k=new Map;#C=new Map;#M=new e.Mutex.Mutex;#N;#x=new Map;#L=!1;#R=[];constructor(e,t){super(),this.#f=e,this.#w=e.pageAgent(),this.#m=e.targetAgent(),this.#y=n.NetworkManager.MultitargetNetworkManager.instance();const r=e.model(n.ResourceTreeModel.ResourceTreeModel);if(!r)throw new Error("ResourceTreeModel is missing for the target: "+e.id());this.#v=r,this.#f=e,this.#N={title:t.title,selectorAttribute:t.selectorAttribute,steps:[]},this.#R=t.selectorTypesToRecord}cloneUserFlow(){return structuredClone(this.#N)}overwriteUserFlow(e){this.#N=structuredClone(e)}async start(){if(this.#L)throw new Error("The session has started");this.#L=!0,await this.#w.invoke_setPrerenderingAllowed({isAllowed:!1}),this.#y.addEventListener(n.NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged,this.#F,this),await this.#A(),await this.#w.invoke_bringToFront(),await this.#P(this.#f)}async stop(){await this.#w.invoke_setPrerenderingAllowed({isAllowed:!0}),await this.#_(),this.#M.acquire(),await Promise.all([...this.#b.values()].map(this.#I)),this.#y.removeEventListener(n.NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged,this.#F,this)}async#A(){const e=this.#v.mainFrame;if(!e)throw new Error("Could not find mainFrame.");this.#y.networkConditions()!==n.NetworkManager.NoThrottlingConditions&&this.#F();const{cssLayoutViewport:t}=await this.#f.pageAgent().invoke_getLayoutMetrics();this.#O(We(t));const r=await this.#v.navigationHistory();if(r){const e=r.entries[r.currentIndex];this.#S.set(this.#f.id(),e.id),this.#E.set(this.#f.id(),r.entries.map((e=>e.id))),this.#N.steps.push({type:c.Navigate,url:e.url,assertedEvents:[{type:l.Navigation,url:e.url,title:e.title}]})}else this.#N.steps.push({type:c.Navigate,url:e.url,assertedEvents:[{type:l.Navigation,url:e.url,title:await this.#$(this.#f)}]});this.#_()}async#$(e){return(await e.runtimeAgent().invoke_evaluate({expression:"document.title"})).result?.value||""}#F(){const e=this.#y.networkConditions();this.#O(Ue(e))}#D;#j=[];#_(){return this.#D&&clearTimeout(this.#D),this.#D=setTimeout((()=>{this.dispatchEventToListeners("recordingupdated",structuredClone(this.#N)),this.#D=void 0;for(const e of this.#j)e();this.#j.length=0}),100),new Promise((e=>{this.#j.push(e)}))}get#W(){return this.#N.steps.slice(-1)[0]}#U=new Set;#O(e){switch(e.type){case"doubleClick":for(let t=this.#N.steps.length-1;t>0;t--){const r=this.#N.steps[t];if("click"===r.type){e.selectors=r.selectors,this.#N.steps.splice(t,1);break}}break;case"change":{const t=this.#W;if(!t)break;switch(t.type){case"change":if(!Be(e,t))break;return this.#N.steps[this.#N.steps.length-1]=e,void this.#_();case"keyDown":return this.#U.add(t.key),this.#N.steps.pop(),void this.#O(e)}break}case"keyDown":if(this.#U.has(e.key))return;break;case"keyUp":if(this.#U.has(e.key))return void this.#U.delete(e.key)}this.#N.steps.push(e),this.#_()}#B(e,t){const r=this.#N.steps[this.#N.steps.length-1];if(r&&!r.assertedEvents?.find((e=>e.type===l.Navigation))){const n=e.target||"main",i=(e.frame||[]).join(","),a=r.target||"main",o=(("frame"in r?r.frame:[])||[]).join(",");n===a&&i===o&&(r.assertedEvents=[{type:l.Navigation}],this.#x.set(t.id(),r),this.#_())}}#K(e,t){const r=this.#x.get(e.id());if(!r)return;const n=r;if(!n.assertedEvents)return;const i=n.assertedEvents.find((e=>e.type===l.Navigation));i&&!i.url&&(i.url=t.url,i.title=t.title,this.#_())}#V(e){const t=Number(e.data.payload);for(let e=0;e<t-1;e++)this.#N.steps.pop();this.dispatchEventToListeners("recordingstopped",structuredClone(this.#N))}#z(e,t){switch(t.data.name){case Qe.stopShortcut:return void this.#V(t);case Qe.addStep:return void this.#H(e,t);default:return}}#H(e,t){const r=t.data.executionContextId;let i;const a=e.model(n.RuntimeModel.RuntimeModel);if(a)for(const e of a.executionContexts())if(e.id===r){i=e.frameId;break}if(!i)throw new Error("No execution context found for the binding call + "+JSON.stringify(t.data));const o=JSON.parse(t.data.payload),s=e.model(n.ResourceTreeModel.ResourceTreeModel).frameForId(i);if(!s)throw new Error("Could not find frame.");const c=Je(e,s);if("beforeUnload"!==o.type)switch(o.type){case"change":this.#O({type:"change",value:o.value,selectors:o.selectors,frame:c.frame.length?c.frame:void 0,target:c.target});break;case"doubleClick":this.#O({type:"doubleClick",target:c.target,selectors:o.selectors,offsetY:o.offsetY,offsetX:o.offsetX,frame:c.frame.length?c.frame:void 0,deviceType:o.deviceType,button:o.button});break;case"click":this.#O({type:"click",target:c.target,selectors:o.selectors,offsetY:o.offsetY,offsetX:o.offsetX,frame:c.frame.length?c.frame:void 0,duration:o.duration,deviceType:o.deviceType,button:o.button});break;case"keyUp":this.#O({type:"keyUp",key:o.key,frame:c.frame.length?c.frame:void 0,target:c.target});break;case"keyDown":this.#O({type:"keyDown",frame:c.frame.length?c.frame:void 0,target:c.target,key:o.key});break;default:throw new Error("Unhandled client event")}else this.#B(c,e)}#J(){return(e=>{const t=[];for(const n of e)for(const e of n){const n={meta:!1,ctrl:!1,shift:!1,alt:!1,keyCode:-1},{keyCode:i,modifiers:a}=r.KeyboardShortcut.KeyboardShortcut.keyCodeAndModifiersFromKey(e);n.keyCode=i;const o=r.KeyboardShortcut.Modifiers;n.ctrl=Boolean(a&o.Ctrl),n.meta=Boolean(a&o.Meta),n.shift=Boolean(a&o.Shift),n.shift=Boolean(a&o.Alt),-1!==n.keyCode&&t.push(n)}return t})(r.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction("chrome_recorder.start-recording").map((e=>e.descriptors.map((e=>e.key)))))}static get#X(){try{return e.Settings.Settings.instance().settingForTest("untrustedRecorderEvents"),!0}catch{}return!1}#P=async e=>{if(e.type()!==n.Target.Type.Frame)return;this.#b.set(e.id(),e);const t=e.model(n.AccessibilityModel.AccessibilityModel);a.assertNotNullOrUndefined(t),await t.resumeModel(),await this.#Y(e),await this.#G(e);const r=e.model(n.ChildTargetManager.ChildTargetManager);a.assertNotNullOrUndefined(r),this.#C.set(e,[r.addEventListener(n.ChildTargetManager.Events.TargetCreated,this.#q.bind(this,e)),r.addEventListener(n.ChildTargetManager.Events.TargetDestroyed,this.#Q.bind(this,e)),r.addEventListener(n.ChildTargetManager.Events.TargetInfoChanged,this.#Z.bind(this,e))]),await Promise.all(r.childTargets().map(this.#P))};#I=async t=>{const r=this.#C.get(t);r&&e.EventTarget.removeEventListeners(r),await this.#ee(t),await this.#te(t)};async#Y(e){const t=e.model(n.RuntimeModel.RuntimeModel);a.assertNotNullOrUndefined(t),this.#k.set(e,[t.addEventListener(n.RuntimeModel.Events.BindingCalled,this.#z.bind(this,e))]),await Promise.all(Object.values(Qe).map((e=>t.addBinding({name:e,executionContextName:o.DEVTOOLS_RECORDER_WORLD_NAME}))))}async#te(t){await Promise.all(Object.values(Qe).map((e=>t.runtimeAgent().invoke_removeBinding({name:e}))));const r=this.#k.get(t);r&&e.EventTarget.removeEventListeners(r)}async#G(e){const t=`\n      ${await o.InjectedScript.get()};DevToolsRecorder.startRecording({getAccessibleName, getAccessibleRole}, {\n        debug: ${o.isDebugBuild},\n        allowUntrustedEvents: ${Ze.#X},\n        selectorTypesToRecord: ${JSON.stringify(this.#R)},\n        selectorAttribute: ${this.#N.selectorAttribute?Ge(this.#N.selectorAttribute):void 0},\n        stopShortcuts: ${JSON.stringify(this.#J())},\n      });\n    `,[{identifier:r}]=await Promise.all([e.pageAgent().invoke_addScriptToEvaluateOnNewDocument({source:t,worldName:o.DEVTOOLS_RECORDER_WORLD_NAME,includeCommandLineAPI:!0}),Xe(o.DEVTOOLS_RECORDER_WORLD_NAME,e,t)]);this.#T.set(e.id(),r)}async#ee(e){const t=this.#T.get(e.id());t&&(await e.pageAgent().invoke_removeScriptToEvaluateOnNewDocument({identifier:t}),await(async(e,t,r)=>{await Promise.all(t.map((t=>Xe(e,t,r))))})(o.DEVTOOLS_RECORDER_WORLD_NAME,[...this.#b.values()],"DevToolsRecorder.stopRecording()"))}#q(e,t){this.#re({type:"targetCreated",event:t,target:e})}#Q(e,t){const r=this.#b.get(t.data);r&&this.#re({type:"targetClosed",event:t,target:r})}#Z(e,t){const r=this.#b.get(t.data.targetId)||e;this.#re({type:"targetInfoChanged",event:t,target:r})}#re(e){return this.#M.run((async()=>{try{switch(o.isDebugBuild&&console.time(`Processing ${JSON.stringify(e)}`),e.type){case"targetClosed":await this.#ne(e);break;case"targetCreated":await this.#ie(e);break;case"targetInfoChanged":await this.#ae(e)}o.isDebugBuild&&console.timeEnd(`Processing ${JSON.stringify(e)}`)}catch(e){console.error("Error happened while processing recording events: ",e.message,e.stack)}}))}async#ie(e){if("page"!==e.event.data.type&&"iframe"!==e.event.data.type)return;await this.#m.invoke_attachToTarget({targetId:e.event.data.targetId,flatten:!0});const t=n.TargetManager.TargetManager.instance().targets().find((t=>t.id()===e.event.data.targetId));if(!t)throw new Error("Could not find target.");await this.#P(t),window.dispatchEvent(new Event("recorderAttachedToTarget"))}async#ne(e){const t=this.#x.get(e.target.id());t&&(delete t.assertedEvents,this.#x.delete(e.target.id()))}async#oe(e,t){const r=await e.navigationHistory();if(!r)return!1;const n=r.entries[r.currentIndex];if(this.#S.get(t.id())===n.id)return!0;this.#S.set(t.id(),n.id);const i=this.#E.get(t.id())||[];if(this.#E.set(t.id(),r.entries.map((e=>e.id))),qe.has(n.transitionType)||i.includes(n.id)){const e=this.#x.get(t.id());e&&(delete e.assertedEvents,this.#x.delete(t.id())),this.#O({type:c.Navigate,url:n.url,assertedEvents:[{type:l.Navigation,url:n.url,title:n.title}]})}else this.#K(t,{type:l.Navigation,url:n.url,title:n.title});return!0}async#ae(e){if("page"!==e.event.data.type&&"iframe"!==e.event.data.type)return;const t=e.target,r=t.model(n.ResourceTreeModel.ResourceTreeModel);if(!r)throw new Error("ResourceTreeModel is missing in handleNavigation");if("iframe"===e.event.data.type)this.#K(t,{type:l.Navigation,url:e.event.data.url,title:await this.#$(t)});else if("page"===e.event.data.type){if(await this.#oe(r,t))return;await this.#se(r,500),this.#K(t,{type:l.Navigation,url:e.event.data.url,title:await this.#$(t)})}}async#se(e,t){let r=()=>Promise.resolve();const i=new Promise((e=>{r=e})),a=()=>{e.removeEventListener(n.ResourceTreeModel.Events.DOMContentLoaded,a),r()};e.addEventListener(n.ResourceTreeModel.Events.DOMContentLoaded,a),await Promise.any([i,new Promise((r=>setTimeout((()=>{e.removeEventListener(n.ResourceTreeModel.Events.DOMContentLoaded,a),r()}),t)))])}}var et=Object.freeze({__proto__:null,RecordingSession:Ze}),tt=Object.freeze({__proto__:null});let rt=null;class nt{next(){return crypto.randomUUID()}}class it{#ce;#M=new e.Mutex.Mutex;#le=new nt;constructor(){this.#ce=e.Settings.Settings.instance().createSetting("recorder_recordings_ng",[])}clearForTest(){this.#ce.set([]),this.#le=new nt}setIdGeneratorForTest(e){this.#le=e}async saveRecording(e){const t=await this.#M.acquire();try{const r=await this.#ce.forceGet(),n={storageName:this.#le.next(),flow:e};return r.push(n),this.#ce.set(r),n}finally{t()}}async updateRecording(e,t){const r=await this.#M.acquire();try{const n=await this.#ce.forceGet(),i=n.find((t=>t.storageName===e));if(!i)throw new Error("No recording is found during updateRecording");return i.flow=t,this.#ce.set(n),i}finally{r()}}async deleteRecording(e){const t=await this.#M.acquire();try{const r=await this.#ce.forceGet();this.#ce.set(r.filter((t=>t.storageName!==e)))}finally{t()}}getRecording(e){return this.#ce.get().find((t=>t.storageName===e))}getRecordings(){return this.#ce.get()}static instance(){return rt||(rt=new it),rt}}var at=Object.freeze({__proto__:null,RecordingStorage:it});let ot=null;class st{#de;#ue;#pe;constructor(t=52428800){this.#de=e.Settings.Settings.instance().createSetting("recorder_screenshots",[]),this.#ue=this.#ge(),this.#pe=t}clear(){this.#de.set([]),this.#ue=new Map}getScreenshotForSection(e,t){const r=this.#ue.get(this.#he(e,t));return r?(this.#fe(r),r.data):null}storeScreenshotForSection(e,t,r){const n={recordingName:e,index:t,data:r};this.#ue.set(this.#he(e,t),n),this.#fe(n)}deleteScreenshotsForRecording(e){for(const[t,r]of this.#ue)r.recordingName===e&&this.#ue.delete(t);this.#fe()}#he(e,t){return`${e}:${t}`}#ge(){const e=new Map,t=this.#de.get();for(const r of t)e.set(this.#he(r.recordingName,r.index),r);return e}#fe(e){if(e){const t=this.#he(e.recordingName,e.index);this.#ue.delete(t),this.#ue.set(t,e)}const t=[];let r=0;for(const[e,n]of Array.from(this.#ue.entries()).reverse())r<this.#pe?(r+=n.data.length,t.push(n)):this.#ue.delete(e);this.#de.set(t.reverse())}static instance(e={forceNew:null,maxStorageSize:52428800}){const{forceNew:t,maxStorageSize:r}=e;return ot&&!t||(ot=new st(r)),ot}}var ct=Object.freeze({__proto__:null,ScreenshotStorage:st});async function lt(e){const t=new Image,r=new Promise((e=>{t.onload=e}));t.src=e,await r;const n=document.createElement("canvas"),i=n.getContext("2d");if(!i)throw new Error("Could not create context.");const a=t.width/t.height;n.width=160,n.height=Math.min(240,160/a);const o=await createImageBitmap(t,{resizeWidth:160,resizeQuality:"high"});return i.drawImage(o,0,0),n.toDataURL("image/png")}var dt=Object.freeze({__proto__:null,resizeScreenshot:lt,takeScreenshot:async function(){const e=await async function(){const e=n.TargetManager.TargetManager.instance().primaryPageTarget();if(!e)throw new Error("Could not find main target");const{data:t}=await e.pageAgent().invoke_captureScreenshot({});return"data:image/png;base64,"+t}();return await lt(e)}});function ut(e){const t=e.assertedEvents?.find((e=>"navigation"===e.type));return"navigate"===e.type?{title:t?.title||"",url:e.url,steps:[],causingStep:e}:t?{title:t.title||"",url:t.url||"",steps:[]}:null}var pt=Object.freeze({__proto__:null,buildSections:function(e){let t=null;const r=[];for(const n of e){if(t)t.steps.push(n);else{if("navigate"===n.type){t=ut(n);continue}t={title:"Current page",url:"",steps:[n]}}const e=ut(n);e&&(t&&r.push(t),t=e)}return!t||r.length&&!t.steps.length||r.push(t),r}});var gt=Object.freeze({__proto__:null,getTooltipForActions:function(e,t){let n=e;const i=r.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction(t);for(const e of i)n+=` - ${e.title()}`;return n}});export{d as ConverterIds,Pe as RecorderSettings,_e as RecorderShortcutHelper,je as RecordingPlayer,et as RecordingSession,tt as RecordingSettings,at as RecordingStorage,Ye as SDKUtils,Le as Schema,ze as SchemaUtils,ct as ScreenshotStorage,dt as ScreenshotUtils,pt as Section,gt as Tooltip};
